package com.lovezy.platform.core.valid.validators;


import com.lovezy.platform.core.exception.ValidationException;
import com.lovezy.platform.core.valid.Validator;
import com.lovezy.platform.core.valid.annotation.Decimal;

import java.lang.annotation.Annotation;
import java.math.BigDecimal;

/**
 *
 * DECIMAL校验器
 *
 */
public class DecimalValidator implements Validator {

	/**
	 * 默认 数据大小为 decimal(15,2)
	 */
	private final int DEFAULT_SCALE = 15;

	private final int DEFAULT_PRECISION = 2;

	private final BigDecimal DEFAULT_MAX = BigDecimal.TEN.pow(DEFAULT_SCALE - DEFAULT_PRECISION);

	public void validate(Object value, Annotation annotation) {
		Decimal an = (Decimal) annotation;
		int scale = an.scale();
		int precision = an.precision();
		BigDecimal max = calMax(scale, precision);
		try {
			BigDecimal b = (BigDecimal) value;
			if (an.greaterThanZero()&&b.compareTo(BigDecimal.ZERO) <= 0) {
				throw new RuntimeException();
			}
			if(b.compareTo(max)>0)
				throw new RuntimeException();

		} catch (Exception e) {
			throw new ValidationException(an.errorCode(), an.errorMsg());
		}

	}

	/**
	 * 根据scale 和 precision 得到 最大值
	 * @param scale
	 * @param precision
	 * @return
	 */
	private BigDecimal calMax(int scale,int precision) {
		if (scale == DEFAULT_SCALE && precision == DEFAULT_PRECISION) {
			return DEFAULT_MAX;
		}
		return BigDecimal.TEN.pow(scale - precision);
	}


}
